#include <iostream>
#include <cstring>
#include <unistd.h>
#include <fcntl.h>

void SetUnblock(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if(fl < 0)
    {
        perror("fcntl");
        return;
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}

int main()
{
    char buff[64];
    SetUnblock(0);
    while(true)
    {
        std::cout << "echo>> ";
        fflush(stdout);
        int n = read(0, buff, sizeof(buff) - 1);
        if(n > 0)
        {
            buff[n - 1] = 0;
            std::cout << buff << std::endl;
        }
        else if(n == 0)
        {
            std::cout << "end of file" << std::endl;
            break;
        }
        else
        {
            if(errno == EAGAIN || errno == EWOULDBLOCK) // 非阻塞轮询时，所返回的错误码
            {
                sleep(1);
                std::cout << std::endl;
                continue;
            }
            else if(errno == EINTR) // 准备读取数据时，却被信号中断所返回的错误码
            {
                sleep(1);
                std::cout << std::endl;
                continue;
            }

            std::cerr << "read error, " << strerror(errno) << ", " << errno << std::endl;
            break;
        }
    }
    return 0;
}